import 'package:cached_network_image/cached_network_image.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:taonile/config/config.dart';

import '../entity/product_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../tabview/order_list.dart';
import '../utils/common_utils.dart';
import '../views/dialog_manager.dart';

///
/// 商品专区
///
class ProductSpecialAreaPage extends StatefulWidget {
  String pageTitle = "";
  String areaId = '';

  ProductSpecialAreaPage({Key? key, this.pageTitle = "", this.areaId = ''}) : super(key: key);

  @override
  State<ProductSpecialAreaPage> createState() => _ProductSpecialAreaPageState();
}

class _ProductSpecialAreaPageState extends State<ProductSpecialAreaPage> {
  var tabNames = [
    '国外精品',
    '母婴用品',
    '电子科技',
    '箱包皮具',
    '服饰鞋帽',
  ];
  int _currentIndex = 0;

  List<ProductData> datas = [];
  var page = 1;

  @override
  void initState() {
    super.initState();
    getProducts();
  }

  getProducts() async {
    var param = {'page': page.toString(), 'size': '20'};
    if (widget.areaId.isNotEmpty) {
      param['area_id'] = widget.areaId;
    }
    dynamic result = await Api.goodsList(param);
    ProductEntity entity = ProductEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  //返回菜单item
  getMenuItem(int position) {
    return InkWell(
      onTap: () {
        setState(() {
          _currentIndex = position;
        });
      },
      child: Container(
        width: 150.w,
        decoration: BoxDecoration(color: Colors.transparent),
        padding: EdgeInsets.fromLTRB(0.w, 0, 0.w, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _currentIndex == position
                ? Text(
                    tabNames[position],
                    style: TextStyle(color: (Config.colorMain), fontSize: 25.sp),
                  )
                : Text(
                    tabNames[position],
                    style: TextStyle(color: (Config.colorText1), fontSize: 25.sp),
                  ),
            Opacity(
              opacity: _currentIndex == position ? 1 : 0,
              child: Container(
                width: 50.w,
                margin: EdgeInsets.only(top: 6.w),
                child: Divider(
                  color: Config.colorMain,
                  height: 3.w,
                  thickness: 3.w,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  //返回商品列表item
  getListItem(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.productDetail, params: {'productId': datas[index].id});
      },
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(10.w),
        ),
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(10.w),
              child: CachedNetworkImage(
                imageUrl: CommonUtils.compressImageUrl(datas[index].mainImg, 500, 500),
                fit: BoxFit.fill,
                width: double.infinity,
                height: 330.w,
                errorWidget: (context, url, error) {
                  return Image.asset(
                    'assets/images/bg_default_400.png',
                    width: double.infinity,
                    height: 330.w,
                    fit: BoxFit.fill,
                  );
                },
              ),
            ),
            Padding(padding: EdgeInsets.all(5.w)),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              width: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(padding: EdgeInsets.only(top: 2.w)),
                  Text(
                    datas[index].name,
                    softWrap: false,
                    style: TextStyle(color: Config.colorText1, fontSize: 28.sp),
                  ),
                  Padding(padding: EdgeInsets.only(top: 10.w)),
                  // Text(
                  //   '商品一句话简介',
                  //   style: TextStyle(color: Config.colorText3, fontSize: 24.sp),
                  //   overflow: TextOverflow.ellipsis,
                  //   maxLines: 1,
                  // ),
                  // Padding(padding: EdgeInsets.only(top: 10.w)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        CommonUtils.formatAmountUnit(datas[index].money, datas[index].company,
                            datas[index].money1, datas[index].company1),
                        style: TextStyle(color: Colors.redAccent, fontSize: 24.sp),
                      ),
                      // Text(
                      //   '销量${datas[index].salesNum}',
                      //   style: TextStyle(color: Config.colorText3, fontSize: 24.sp),
                      // ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: Text(widget.pageTitle),
        centerTitle: true,
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            // Container(
            //   decoration: BoxDecoration(color: Config.colorWhite),
            //   width: double.infinity,
            //   height: 65.w,
            //   child: ListView.builder(
            //     itemCount: tabNames.length,
            //     padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
            //     shrinkWrap: true,
            //     scrollDirection: Axis.horizontal,
            //     physics: const BouncingScrollPhysics(),
            //     itemBuilder: (BuildContext context, int index) {
            //       return getMenuItem(index);
            //     },
            //   ),
            // ),
            Container(
              height: double.infinity,
              width: double.infinity,
              margin: EdgeInsets.only(top: 1.w),
              child: EasyRefresh(
                header: const MaterialHeader(),
                footer: const MaterialFooter(),
                onRefresh: () async {
                  page = 1;
                  getProducts();
                },
                onLoad: () async {
                  getProducts();
                },
                child: GridView.builder(
                  padding: EdgeInsets.symmetric(horizontal: 25.w, vertical: 20.w),
                  itemCount: datas.length,
                  // shrinkWrap: true,
                  // scrollDirection: Axis.vertical,
                  // physics: const BouncingScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return getListItem(index);
                  },
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      mainAxisSpacing: 19.w,
                      crossAxisSpacing: 19.w,
                      childAspectRatio: 0.76),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
